<?php

namespace App\Models;

use App\Http\Controllers\ImgController;
use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品电子书关联表
 * Class ArticleModel
 * @package app\common\model
 */
class CompetiteActivityWorksEbook extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'competite_activity_works_ebook';



    /**
     * 获取作品电子书数量
     * @param ebook_id  电子书id
     */
    public function ebookNumber($ebook_id)
    {
        return $this->where('ebook_id', $ebook_id)->where('is_del', 1)->count();
    }


    /** 
     * 收录作品
     * @param ebook_id int 电子书id
     * @param works_ids int 作品id 多个逗号拼接,一次最多不能选择30个
     */
    public function recordAdd($data)
    {
        $competiteActivityWorksModel = new CompetiteActivityWorks();

        $ids =  $data['works_ids'];
        $ids = explode(',', $ids);
        if (count($ids) > 30) {
            throw new Exception('作品一次最多只能选择30条');
        }
        foreach ($ids as $key => $val) {
            $is_exists = $this->where('ebook_id', $data['ebook_id'])->where('type', 1)->where('works_id', $val)->where('is_del', 1)->first();
            if (empty($is_exists)) {
                //判断当前作品是否只包含图片和文字
                $isCanAddEbook = $competiteActivityWorksModel->isCanAddEbook($val);
                if (is_string($isCanAddEbook)) {
                    throw new Exception($isCanAddEbook);
                }
                //使用文字和图片生成pdf
                $pdfObj = new PdfController();
                //判断文字是否存在，存在则转换为图片
                if (!empty($isCanAddEbook['content'])) {
                    if (!empty($isCanAddEbook['content']) && !empty($isCanAddEbook['img'])) {
                        $content = [
                            '<h2 style="text-align: center">' . $isCanAddEbook['title'] . '</h1>
                            <div style="line-height:20px;color:#666666;text-align:center;">
                            <img src="' . public_path('uploads') . $isCanAddEbook['img'] . '">' . $isCanAddEbook['content'] . '</div>'
                        ];
                    } elseif (!empty($isCanAddEbook['content'])) {
                        $content = [
                            '<h2 style="text-align: center">' . $isCanAddEbook['title'] . '</h1>
                            <div style="line-height:20px;color:#666666;text-align:center;">' . $isCanAddEbook['content'] . '</div>'
                        ];
                    }

                    //保存文字转换为PDF格式
                    $pdf_path = $pdfObj->setPdf(
                        '',
                        $content,
                        null,
                        $isCanAddEbook['serial_number']
                    );
                    //在把pdf转换成图片
                    $img = $pdfObj->pdf2png2($pdf_path, '/ebook_img/');
                } else {
                    $img = $isCanAddEbook['img'];
                }
                $obj = new self();
                $obj->img = $img;
                $obj->ebook_id = $data['ebook_id'];
                $obj->works_id = $val;
                $obj->type = 1;
                $obj->save();

                //新增PDF作品类型
                if (!empty($isCanAddEbook['pdf_works_address'])) {
                    $data['pdf_address'] = $isCanAddEbook['pdf_works_address'];
                    $competiteActivityWorksEbookModel = new CompetiteActivityWorksEbook();
                    $competiteActivityWorksEbookModel->recordAddPdf($data);
                }
            }
        }
        return true;
    }

    /** 
     * 收录作品(图片)
     * @param ebook_id int 电子书id
     * @param ebook_img int 电子书图片 多个 | 拼接
     */
    public function recordAddImg($data)
    {
        $img =  $data['ebook_img'];
        $img = explode(',', $img);
        foreach ($img as $key => $val) {
            $obj = new self();
            $obj->ebook_id = $data['ebook_id'];
            $obj->img = $val;
            $obj->type = 2;
            $obj->save();
        }
        return true;
    }

    /** 
     * 收录作品（电子书）
     * @param ebook_id int 电子书id
     * @param pdf_address int 作品id 多个逗号拼接
     */
    public function recordAddPdf($data)
    {
        $pdf_address =  $data['pdf_address'];
        //pdf转换为多张图片
        $pdfObj = new PdfController();
        $pdf = $pdfObj->pdf2png($pdf_address, '/ebook_img/');
        foreach ($pdf as $key => $val) {
            $obj = new self();
            $obj->ebook_id = $data['ebook_id'];
            $obj->pdf_address = $val;
            $obj->type = 3;
            $obj->save();
        }
        return true;
    }

    /**
     * 删除收录的产品
     * @param id  收录的id
     */
    public function recordDel($id)
    {
        $id = !is_array($id) ? explode(',', $id) : $id;
        return $this->whereIn('id', $id)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
    }
    /**
     * 列表
     * @param ebook_id int 电子书id
     * @param limit int 分页大小
     * @param start_time datetime 创建时间(开始)
     * @param end_time datetime 创建时间(截止)
     * @param type datetime 类型  1 作品选择  2 图片上传  3 pdf 上传
     */
    public function lists($ebook_id, $type, $start_time, $end_time, $limit = 10)
    {
        $res = $this->select('id', 'type', 'create_time', 'sort', 'img', 'works_id', 'pdf_address')
            ->where(function ($query) use ($type, $start_time, $end_time) {
                if ($type) {
                    $query->where('type', $type);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where('ebook_id', $ebook_id)
            ->where('is_del', 1)
            ->orderBy('sort')
            ->paginate($limit)
            ->toArray();
        return $res;
    }
}
